import COS from 'cos-js-sdk-v5';
import {
  getAxios,
  postAxios
} from "@utils/api";
import dayjs from "dayjs";
import randomString from "@utils/randomString";
import notify from "@utils/tip";

const currBucketSet = {
  prefix: '',
  domain: '',
  cos: null,
  credentials: {
    TmpSecretId: "",
    TmpSecretKey: "",
    SecurityToken: "",
    // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
    StartTime: 0,
    ExpiredTime: 0,
  },
  bucket: "",
  region: "",
}

async function getBucketSet(bucketPrefix) {
  if (currBucketSet.cos == null) {

    const data = await getAxios('/admin/api/vendor/v1/cos/bucketSets', {
      app: 'bilin-web',
    })
    
    let matched = data.bucket_sets.find(bs => bs.prefix.startsWith(bucketPrefix))
    if (!matched) {
      notify("bucket不可用", 'error')
      throw "credentials invalid"
    }
    currBucketSet.prefix = matched.prefix
    currBucketSet.bucket = matched.bucket
    currBucketSet.region = matched.region
    currBucketSet.domain = matched.custom_domain

    currBucketSet.cos = new COS({
      // 必选参数
      getAuthorization: function (options, callback) {
        // 服务端 JS 和 PHP 例子：https://github.com/tencentyun/cos-js-sdk-v5/blob/master/server/
        // 服务端其他语言参考 COS STS SDK ：https://github.com/tencentyun/qcloud-cos-sts-sdk
        // STS 详细文档指引看：https://cloud.tencent.com/document/product/436/14048
        // console.log('getAuthorization======>')
        postAxios("/admin/api/vendor/v1/cos/authorization", {
          bucket_prefix: currBucketSet.prefix,
        }).then(data => {
          if (!data || !data.credentials) {
            notify("bucket credentials invalid", 'error')
            return
          }
          var credentials = {
            TmpSecretId: data.credentials.tmp_secret_id,
            TmpSecretKey: data.credentials.tmp_secret_key,
            SecurityToken: data.credentials.session_token,
            // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
            // StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
            ExpiredTime: data.credentials.expired_time, // 时间戳，单位秒，如：1580000900
          }
          currBucketSet.credentials = credentials
          currBucketSet.bucket = data.bucket
          currBucketSet.region = data.region

          callback(credentials);
        })
      }
    })
  }
  return currBucketSet
}


export async function uploadCOSFile(file, firstKey, imageType, successCallback, failureCallback) {
  var bucketSet = await getBucketSet('bgp')
  // console.log('bucketSet=>', bucketSet)
  const key = `${firstKey}_${dayjs().format('YYYYMMDD')}_${randomString(12)}.${imageType}`
  bucketSet.cos.putObject({
    /* 必须 */
    Bucket: bucketSet.bucket,
    /* 存储桶所在地域，必须字段 */
    Region: bucketSet.region,
    /* 必须 */
    Key: key,
    StorageClass: 'STANDARD',
    Body: file, // 上传文件对象
    onProgress: function (progressData) {
      console.log(JSON.stringify(progressData));
    }
  }, function (err, data) {
    if (err) {
      console.error('err =>', err)
      notify(err.message, 'error')
      failureCallback && failureCallback()
      return
    }
    successCallback && successCallback({
      ...data,
      key: `${bucketSet.domain}/${key}`
    })
  });
}